#--------- Date:2017-6-28 ---------
#Owner: baoshan.zhang
#Summary:Class used to fetch fund's daily info such as nav

import pymssql
import pandas as pd
import pandas.io.sql as sql
from pandas import *
from datetime import date,datetime,timedelta
import enum

# Common constant
RiskFreeRate = 0.03

class YieldPeriod(enum.Enum):
    OneYear=1,
    OneMonth=2,
    OneDay=3,
    SinceBorn=4,
    TwoYear=5,
    ThreeYear=6

class FundInfo:
    def __init__(self,fundId):
        # self.conn = pymssql.connect(server='10.101.237.68\SQL2012', user='sa', password='Hua1xia2', database='jgdb2')
        self.fundId = fundId
        # self.conn = pymssql.connect(server='.', user='sa', password='qweqwe', database='jgdb2')
        self.conn = pymssql.connect(server='.', user='sa', password='qweqwe', database='jgdb2')

    #get fund's daily net value as a DataFrame
    def getFundDailyNavInfo(self):
        query = 'SELECT trade_dt,f_nav,f_fund_id ,f_valid  ,f_drawdown,f_marketvalue , ' \
                'f_change FROM ..HsFundNav WHERE f_fund_id=%s and f_valid=1 ORDER BY trade_dt' % self.fundId
        df = sql.read_sql(query,self.conn,index_col=['trade_dt'],parse_dates=['trade_dt'])
        # self.conn.close()
        return df

    #get yield based on given period
    def getYield(self,period):
        netValueDF = self.getFundDailyNavInfo()

        if(period == YieldPeriod.OneYear):
            if(len(netValueDF.index)>252):
                endYield = netValueDF.ix[-1:]['f_nav'].item()
                beginYield = netValueDF.ix[-252]['f_nav'].item(0)
            else:
                return None

        if(period == YieldPeriod.OneMonth):
            if(len(netValueDF.index)>21):
                endYield = netValueDF.ix[-1:]['f_nav'].item()
                beginYield = netValueDF.ix[-21]['f_nav'].item(0)
            else:
                return None

        if(period == YieldPeriod.SinceBorn):
            beginYield = netValueDF.ix[:1]['f_nav'].item()
            endYield = netValueDF.ix[-1:]['f_nav'].item()

        return (endYield - beginYield)/endYield










